package com.appkubes.fintech.restful.application.user.service.impl;

import com.appkubes.fintech.core.po.FintechUserContact;
import com.appkubes.fintech.core.po.FintechUserContactExample;
import com.appkubes.fintech.restful.application.user.domain.UserCertificateDomain;
import com.appkubes.fintech.restful.application.user.entity.dto.EmergencyContactDTO;
import com.appkubes.fintech.restful.application.user.dao.UserContactDao;
import com.appkubes.fintech.restful.application.user.entity.vo.UserContactInfoVO;
import com.appkubes.fintech.restful.application.user.service.UserContactService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户关系表 服务实现类
 * </p>
 *
 * @author wuzhijian
 * @since 2019-12-26
 */
@Service
@Slf4j
@Data
public class UserContactServiceImpl implements UserContactService {

    @Resource
    UserContactDao userContactDao;

    @Resource
    UserCertificateDomain certificateService;


    @Override
    @Transactional
    public Integer saveEmergencyContact(UserContactInfoVO userContactInfoVO) {
        Integer effectRow = 0;
        String userKey = userContactInfoVO.getUserKey();

        //清掉旧的数据，重新添加
        FintechUserContactExample example = new FintechUserContactExample();
        example.createCriteria().andUserKeyEqualTo(userContactInfoVO.getUserKey());
        userContactDao.deleteByExample(example);
        List<EmergencyContactDTO> contactInfoList = userContactInfoVO.getEmergencyContactDTOList();
        for (EmergencyContactDTO contactInfo : contactInfoList) {
            FintechUserContact fintechUserContact = new FintechUserContact();
            BeanUtils.copyProperties(contactInfo, fintechUserContact);
            fintechUserContact.setUserKey(userKey);
            fintechUserContact.setUpdateTime(new Date());
            fintechUserContact.setWork(contactInfo.getWork());
            effectRow += userContactDao.insertSelective(fintechUserContact);
        }
        effectRow += certificateService.updateContactCertificate(userContactInfoVO.getUserKey(), 1);


        return effectRow;
    }
}
